<template>
  <el-form>
    <el-row>
      <el-col :span="24">
        <el-form-item label="报表类型:">
          <CustomSelect
            :options="type_list"
            ref="report"
            v-if="template_show"
          ></CustomSelect>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="公司列表:">
          <CustomSelect
            :options="company_list"
            ref="company"
            v-if="company_show"
          ></CustomSelect>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :span="24">
      <el-form-item>
        <el-button type="primary" @click="submit">
          生成报表
          <i class="el-icon-download el-icon--right"></i>
        </el-button>
      </el-form-item>
    </el-row>
  </el-form>
</template>

<script>
import CustomSelect from "@/components/CustomSelect.vue";

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "Report",
  components: {
    CustomSelect,
  },
  data: function () {
    return {
      template_show: false,
      company_show: false,
      metadata: [], // 元数据
      metadata_subsidiary: [], // 含有子公司的模板集合
      link_id_arr: [],
      type_list: [
        {
          id: "management_standard",
          value: "管理标准",
          disable: false,
        },
        {
          id: "technical_standard",
          value: "技术标准",
          disable: false,
        },
        {
          id: "job_description",
          value: "岗位说明",
          disable: false,
        },
        {
          id: "work_standard",
          value: "工作标准",
          disable: false,
        },
        {
          id: "operating_standard",
          value: "操作标准",
          disable: false,
        },
        {
          id: "record",
          value: "记录",
          disable: false,
        },
        {
          id: "equipment_manual",
          value: "设备说明书",
          disable: false,
        },
      ],
      company_list: [
        {
          id: "0",
          value: "云南通威",
          disable: false,
        },
        {
          id: "1",
          value: "永祥新材料",
          disable: false,
        },
        // { id: "2", value: "通威总部", disable: false },
        // { id: "3", value: "永祥硅材料", disable: false },
        // { id: "4", value: "通威绿能电力", disable: false },
        // { id: "5", value: "永祥新能源", disable: false },
        // { id: "6", value: "永祥树脂", disable: true },
        // { id: "7", value: "永祥光伏科技", disable: true },
        // { id: "8", value: "内蒙古通威", disable: true },
        // { id: "9", value: "永祥多晶硅", disable: true },
        // { id: "10", value: "永祥能源科技", disable: true },
      ],
    };
  },
  methods: {
    async submit() {
      // const checked_type = "已选择报表：" + this.$refs.report.checkedTypes;
      // const checked_company =
      //   "已选择子公司：" + this.$refs.company.checkedTypes;
      // console.log(checked_type + "\n" + checked_company);

      // 获取子公司名
      // const checked_report = [];

      if (this.$refs.report.checkedTypes.length === 0) {
        alert("请选择报表类型");
        return false;
      }

      if (this.$refs.company.checkedTypes.length === 0) {
        alert("请选择子公司");
        return false;
      }

      const checked_report = [];
      const checked_company = [];
      for (let i = 0; i < this.$refs.report.checkedTypes.length; i++) {
        for (let n = 0; n < this.type_list.length; n++) {
          if (this.$refs.report.checkedTypes[i] === this.type_list[n]["id"]) {
            checked_report.push(this.type_list[n]);
          }
        }
      }

      for (let i = 0; i < this.$refs.company.checkedTypes.length; i++) {
        for (let n = 0; n < this.company_list.length; n++) {
          if (
            this.$refs.company.checkedTypes[i] == this.company_list[n]["id"]
          ) {
            checked_company.push({id: this.company_list[n]["id"], value: this.company_list[n]["value"], data: []});
          }
        }
      }

      console.log("checked_report");
      console.log(checked_report);

      console.log("checked_company");
      console.log(checked_company);

      for (let i = 0; i < checked_report.length; i++) {
        for (let n = 0; n < checked_company.length; n++) {

          let get_file_docid = await this.axios
            .post("/api/ecosearch/v1/file-search", {
              condition: {},
              custom: [
                {
                  isTemplate: true,
                  scope: "aishu",
                  key: checked_report[i]["subsidiary_key"], // field字段名称
                  mode: "in",
                  type: "multiselect",
                  template: checked_report[i]["id"], // 模板名称
                  value: [checked_company[n]["value"]],
                },
              ],
              dimension: [],
              keyword: "",
              range: [],
              rows: 50,
              start: 0,
              type: "doc",
            })
            .then((get_file_docid) => [null, get_file_docid])
            .catch((err) => [err, null]);

          if (!get_file_docid[1]) {
            // microWidgetProps.components.toast.error(JSON.stringify(get_info_by_path[1]));
            alert(JSON.stringify(get_file_docid[1]));
            return false;
          }

          get_file_docid = get_file_docid[1];

          if (get_file_docid.data.files.length != 0) {
            let docidArr = [];
            for(let i = 0; i<get_file_docid.data.files.length; i++){
              docidArr.push(get_file_docid.data.files[i]["doc_id"]);
            }
            console.log("docidArr");
            console.log(docidArr);

            checked_company[n]["data"].push({
              template: checked_report[i],
              docid_arr: docidArr
            })
          }

          console.log("get_file_docid");
          console.log(get_file_docid);

        //   this.axios({
        //     method: "POST",
        //     url: "/api/ecosearch/v1/file-search",
        //     data: {
        //       condition: {},
        //       custom: [
        //         {
        //           isTemplate: true,
        //           scope: "aishu",
        //           key: checked_report[i]["subsidiary_key"], // field字段名称
        //           mode: "in",
        //           type: "multiselect",
        //           template: checked_report[i]["id"], // 模板名称
        //           value: [checked_company[n]["value"]],
        //         },
        //       ],
        //       dimension: [],
        //       keyword: "",
        //       range: [],
        //       rows: 50,
        //       start: 0,
        //       type: "doc",
        //     },
        //   })
        //     .then((res) => {
        //       console.log("/api/ecosearch/v1/file-search");
        //       console.log(res);

        //       if (res.data.files.length != 0) {
        //         console.log("res.data.files.length != 0");
        //       }
        //     })
        //     .catch((error) => {
        //       console.log(error);
        //     });
        }
      }

      console.log("生成的checked_company");
      console.log(checked_company);

      // console.log("this.$refs.report.checkedTypes");
      // console.log(this.$refs.report.checkedTypes);

      // console.log("this.$refs.company.checkedTypes");
      // console.log(this.$refs.company.checkedTypes);

      // console.log("checked_report");
      // console.log(checked_report);

      // console.log("checked_company");
      // console.log(checked_company);

      // this.axios({
      //   method: "POST",
      //   url: "/api/ecosearch/v1/file-search",
      //   data: {
      //     condition: {},
      //     custom: [
      //       {
      //         isTemplate: true,
      //         scope: "aishu",
      //         key: "field_jpjjfcry1j", // 字段名称
      //         mode: "in",
      //         type: "multiselect",
      //         template: "template_2pzkz09vubk", // 模板名称
      //         value: ["永祥新能源"],
      //       },
      //     ],
      //     dimension: [],
      //     keyword: "",
      //     range: [],
      //     rows: 50,
      //     start: 0,
      //     type: "doc",
      //   },
      // })
      //   .then((res) => {
      //     console.log("/api/ecosearch/v1/file-search");
      //     console.log(res);
      //   })
      //   .catch((error) => {
      //     console.log(error);
      //   });
    },
    async getLinkId(gns) {
      // step 1
      let name_path = await this.axios
        .post("/api/efast/v1/file/convertpath", {
          docid: gns,
        })
        .then((name_path) => [null, name_path])
        .catch((err) => [err, null]);

      if (!name_path[1]) {
        // microWidgetProps.components.toast.error(JSON.stringify(name_path[1]));
        alert(JSON.stringify(name_path[1]));
        return false;
      }

      name_path = name_path[1];

      // step 2
      let get_info_by_path = await this.axios
        .post("/api/efast/v1/file/getinfobypath", {
          namepath: name_path.data.namepath,
        })
        .then((get_info_by_path) => [null, get_info_by_path])
        .catch((err) => [err, null]);

      if (!get_info_by_path[1]) {
        // microWidgetProps.components.toast.error(JSON.stringify(get_info_by_path[1]));
        alert(JSON.stringify(get_info_by_path[1]));
        return false;
      }

      get_info_by_path = get_info_by_path[1];

      // step 3
      let get_id = await this.axios
        .get(
          "/api/shared-link/v1/document/file/" +
            encodeURIComponent(get_info_by_path.data.docid) +
            "?type=realname"
        )
        .then((get_id) => [null, get_id])
        .catch((err) => [err, null]);

      if (!get_id[1]) {
        // microWidgetProps.components.toast.error(JSON.stringify(get_id[1]));
        alert(JSON.stringify(get_id[1]));
        return false;
      }

      get_id = get_id[1];

      let link_id;

      if (get_id.data.length > 0) {
        link_id = get_id.data[0].id;
      } else {
        let _get_id = await this.axios
          .post("/api/shared-link/v1/document/realname", {
            item: {
              id: get_info_by_path.data.docid,
              type: "file",
            },
          })
          .then((_get_id) => [null, _get_id])
          .catch((err) => [err, null]);

        if (!_get_id[1]) {
          // microWidgetProps.components.toast.error(JSON.stringify(_get_id[1]));
          alert(JSON.stringify(_get_id[1]));
          return false;
        }

        _get_id = _get_id[1];

        link_id = _get_id.data.id;
      }

      this.link_id_arr.push(link_id);
    },
    async getFileItem(file_id) {
      let file_item = await this.axios
        .get(`https://anyshare.izhen.top/api/metadata/v1/item/${file_id}/mdata`)
        .then((file_item) => [null, file_item])
        .catch((err) => [err, null]);

      if (!file_item[1]) {
        // microWidgetProps.components.toast.error(JSON.stringify(name_path[1]));
        alert(JSON.stringify(file_item[1]));
        return false;
      }

      file_item = file_item[1];

      console.log("file_item");
      console.log(file_item);
    },
  },
  beforeCreate() {
    const _this = this;
    this.axios({
      method: "GET",
      url: `/api/metadata/v1/templates`,
    })
      .then((res) => {
        console.log("获取到的元素据：");
        console.log(res.data.entries);
        const type_list = [];
        const company_list = [];
        // 获取元素据模板列表
        for (let i = 0; i < res.data.entries.length; i++) {
          // type_list.push({
          //   id: res.data.entries[i]["key"] + i,
          //   value: res.data.entries[i]["display_name"],
          //   disable: false,
          // });

          // 获取子公司的key
          for (let n = 0; n < res.data.entries[i]["fields"].length; n++) {
            if (res.data.entries[i]["fields"][n]["display_name"] === "子公司") {
              // 获取含有子公司的模板名称、模板key以及子公司key
              type_list.push({
                id: res.data.entries[i]["key"], // 模板key
                value: res.data.entries[i]["display_name"], // 模板名称
                subsidiary_key: res.data.entries[i]["fields"][n]["key"], //子公司key
                disable: false,
              });

              // _this.metadata_subsidiary.push({
              //   template_key: res.data.entries[i]["key"],
              //   template_name: res.data.entries[i]["display_name"],
              //   subsidiary_key: res.data.entries[i]["fields"][n]["key"],
              // });

              for (
                let m = 0;
                m < res.data.entries[i]["fields"][n]["options"].length;
                m++
              ) {
                company_list.push(
                  res.data.entries[i]["fields"][n]["options"][m]["key"]
                );
              }
            }
          }
        }

        // 去重
        const _company_list = [];
        for (let i = 0; i < company_list.length; i++) {
          if (_company_list.indexOf(company_list[i]) < 0) {
            _company_list.push(company_list[i]);
          }
        }

        const _company_list_ = [];
        for (let i = 0; i < _company_list.length; i++) {
          _company_list_.push({
            id: i,
            value: _company_list[i],
            disable: false,
          });
        }

        _this.metadata = res.data.entries;
        _this.type_list = type_list;
        _this.company_list = _company_list_;
        _this.template_show = true;
        _this.company_show = true;

        console.log("type_list");
        console.log(type_list);
      })
      .catch((error) => {
        console.log(error);
      });
  },
  mounted() {
    this.getLinkId(
      "gns://D0F7A20954DB4375A5D410196575EDFF/A41EA3729BCF4AC1A8447C1C7E15A470"
    );
    console.log("link_id");
    console.log(this.link_id_arr);
    this.getFileItem("A41EA3729BCF4AC1A8447C1C7E15A470");
  },
};
</script>

<style>
.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
